/**
 * TodoItem
 *
 */

import React, { FunctionComponent, CSSProperties, ChangeEvent } from 'react';
import { connect } from 'react-redux';
import classnames from 'classnames';
import { List, Checkbox, Input } from 'antd';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import { TodoItem as TodoItemType } from '../../Stores/Todo/TodoList/types';
import { EditorForm } from '../../Stores/Todo/EditorForm/types';
import styles from './index.scss';

export interface TodoItemProps {
  style?: CSSProperties;
  todoItem: TodoItemType;
  editorForm: EditorForm;
  onToggleTodo: (id: string, isCompleted?: boolean) => void;
  onRemoveTodo: (id: string) => void;
  onChangeEditorVal: (value: string) => void;
  onChangeTargetId: (id: string) => void;
  onUpdateTodo: (id: string, title: string) => void;
}

const TodoItem: FunctionComponent<TodoItemProps> = ({ style, todoItem, editorForm, ...props }) => {
  const isEditing = todoItem.id === editorForm.targetId;
  const onToggleTodo = (event: CheckboxChangeEvent) => props.onToggleTodo(todoItem.id, event.target.checked);
  const onRemoveTodo = () => props.onRemoveTodo(todoItem.id);
  const onChangeTargetId = () => props.onChangeTargetId(todoItem.id);
  const onChangeEditorVal = (event: ChangeEvent<HTMLInputElement>) => props.onChangeEditorVal(event.target.value);
  const onUpdateTodo = () => props.onUpdateTodo(todoItem.id, editorForm.value);

  return (
    <List.Item
      style={style}
      onDoubleClick={onChangeTargetId}
      actions={
        isEditing
          ? []
          : [
              <a key="editor" onClick={onChangeTargetId}>
                编辑
              </a>,
              <a key="delete" onClick={onRemoveTodo}>
                删除
              </a>
            ]
      }
    >
      <div className={styles.todoItem}>
        {isEditing ? (
          <Input value={editorForm.value} onChange={onChangeEditorVal} onBlur={onUpdateTodo} onPressEnter={onUpdateTodo} />
        ) : (
          <React.Fragment>
            <Checkbox checked={todoItem.isCompleted} onChange={onToggleTodo} />
            <span className={classnames(styles.itemText, { [styles.completedItem]: todoItem.isCompleted })}>{todoItem.title}</span>
          </React.Fragment>
        )}
      </div>
    </List.Item>
  );
};

export default connect()(TodoItem);
